package com.lb;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisClientConfig;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.params.SetParams;

import java.util.HashSet;
import java.util.Set;

public class RedisClusterLockDemo {

    private static JedisCluster jedisCluster;

    // 初始化 Redis Cluster 连接
    static {
        Set<HostAndPort> clusterNodes = new HashSet<>();
        clusterNodes.add(new HostAndPort("47.120.36.156", 30001));
      clusterNodes.add(new HostAndPort("47.120.36.156", 30002));
      clusterNodes.add(new HostAndPort("47.120.36.156", 30003));
      clusterNodes.add(new HostAndPort("47.120.36.156", 30004));
      clusterNodes.add(new HostAndPort("47.120.36.156", 30005));
      clusterNodes.add(new HostAndPort("47.120.36.156", 30006));

        // JedisCluster 会自动发现集群拓扑（主从、分片）
       // jedisCluster = new JedisCluster(clusterNodes);
        JedisClientConfig clientConfig = DefaultJedisClientConfig.builder()
                .password("yourpassword")           // ← 替换为你的真实密码
                .connectionTimeoutMillis(2000
                )
                .socketTimeoutMillis(2000
                )
                .build();

        // 3. 创建 JedisCluster 实例
        jedisCluster = new
                JedisCluster(clusterNodes, clientConfig);
    }

    public static void main(String[] args) throws InterruptedException {
        String lockKey = "my:lock";
        String clientId = "client_01";

        try {
            // ✅ 加锁：SET key value NX EX 10

            String result = jedisCluster.set(lockKey, clientId,
                    SetParams.setParams().nx().ex(10)
            );

            if ("OK".equals(result)) {
                System.out.println("✅ 成功获取锁！开始执行业务逻辑...");
                Thread.sleep(5000); // 模拟业务操作
                System.out.println("✅ 业务执行完成。");
            } else {
                System.out.println("❌ 获取锁失败，可能被其他客户端持有。");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // ✅ 释放锁（简单删除，生产环境应加 Lua 脚本校验 clientId）
            jedisCluster.del(lockKey);
            System.out.println("🔓 锁已释放。");
        }

        // 关闭客户端
        try {
            jedisCluster.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
